import tornado.web
from utilspackage.utils import Constant, to_data
from tornado.websocket import WebSocketHandler
import random


class BaseHandler(tornado.web.RequestHandler):
    """定义了一个父类"""

    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        self.set_header("Access-Control-Allow-Headers", "access-control-allow-origin,authorization,content-type")

    def options(self):
        self.set_status(204)
        self.finish()


class MainHandler(BaseHandler):
    """主页"""

    def get(self):
        self.write('hello,world')


class MessageRefreshHandler(WebSocketHandler):
    """
        消息刷新
    """
    users = set()  # 储存在线用户的容器

    def open(self):
        self.users.add(self)
        for user in self.users:
            user.write_message(Constant.OK)

    def on_message(self, message):
        print(message)
        print(self.users)
        for user in self.users:
            user.write_message(to_data({'random': random.randint(0, 10)}))

    def on_close(self):
        self.users.remove(self)
        for user in self.users:
            user.write_message(Constant.OK)

    def check_origin(self, origin):
        return True


class RefreshHandler(BaseHandler):
    def get(self):
        self.render('refresh.html')


class PassivityRefreshHandler(BaseHandler):
    def get(self):
        self.render('passivityRefresh.html')


class MessagePassivityRefreshHandler(WebSocketHandler):
    """
        消息刷新
    """
    users = set()  # 储存在线用户的容器

    def open(self):
        self.users.add(self)
        for user in self.users:
            user.write_message(Constant.OK)

    def on_message(self, message):
        print(message)
        print(self.users)
        for i in range(10000):
            for user in self.users:
                user.write_message(to_data({'random': random.randint(0, 1000)}))

    def on_close(self):
        self.users.remove(self)
        for user in self.users:
            user.write_message(Constant.OK)

    def check_origin(self, origin):
        return True
